import { _decorator, Component, Node, RigidBody, Vec3, input, EventKeyboard, Input, KeyCode, Details, director } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PlayerMovement')
export class PlayerMovement extends Component {

    @property(RigidBody)
    rigidBody: RigidBody;  // 该脚本作用于哪个刚体

    @property(Number)
    forWardForce: number = 0;  // 前进的力

    @property(Number)
    sideForce: number = 0;  // 左右的力

    isLeftDown: boolean = false;  // A是否被按下
    isRightDown: boolean = false;  // D是否被按下

    // 脚本启动时执行一次
    start() {
        // 输入事件监听开启
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
    }

    // 每一帧更新时进行的操作, deltaTime为执行一帧的时间
    update(deltaTime: number) {
        // 自动向前
        let force = new Vec3(0, 0, this.forWardForce * deltaTime);
        this.rigidBody.applyForce(force);
        
        // A按下，给予向左的力
        if(this.isLeftDown) {
            let force = new Vec3(this.sideForce * deltaTime, 0, 0);
            this.rigidBody.applyForce(force);
        }

        // D按下，给予向右的力
        if(this.isRightDown) {
            let force = new Vec3(-this.sideForce * deltaTime, 0, 0);
            this.rigidBody.applyForce(force);
        }

        // 检测是否掉出跑道外
        if(this.node.getPosition().y < -10) {
            console.log('out, you lose');
            // 抛出一个level_failed事件
            director.getScene().emit('level_failed');
            // 屏蔽PlayerMovement
            this.enabled = false;
        }
    }

    // 输入监听的销毁
    onDestroy() {
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.off(Input.EventType.KEY_UP, this.onKeyUp, this);
    }

    // 按键按下执行的回调函数
    onKeyDown(event: EventKeyboard) {
        if(event.keyCode == KeyCode.KEY_A) {
            this.isLeftDown = true;
            console.log("A Down");
        }

        if(event.keyCode == KeyCode.KEY_D) {
            this.isRightDown = true;
            console.log("D Down");
        }
    }

    // 按键弹起执行的回调函数
    onKeyUp(event: EventKeyboard) {
        if(event.keyCode == KeyCode.KEY_A) {
            this.isLeftDown = false;
            console.log("A Up");
        }

        if(event.keyCode == KeyCode.KEY_D) {
            this.isRightDown = false;
            console.log("D Up");
        }
    }

}


